package com.example.cloud.controller.statistics;

import com.example.cloud.controller.common.BaseController;
import com.example.cloud.model.dto.Result;
import com.example.cloud.utils.ResultUtil;
import com.example.cloud.utils.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Created by wt on 2018/10/25.
 */
@RestController
@RequestMapping("/statistics/income")
public class StatisticsIncomeController extends BaseController {

    @Autowired
    private SQLManager sqlManager;

    @PostMapping("/search")
    public Result search(@RequestBody Map params) {
        StringBuilder sql = new StringBuilder("select IFNULL(sum(bank_card),0) as bank,IFNULL(sum(alipay),0) as alipay,IFNULL(sum(wechat),0) as wechat,IFNULL(sum(cash),0) as cash from finance_payment_details");
        if(params.containsKey("startTime") && StringUtils.isNotBlank(params.get("startTime").toString())){
            sql.append(" where creation_time >= '" + params.get("startTime") + "'");
        }
        if(params.containsKey("endTime") && StringUtils.isNotBlank(params.get("endTime").toString())){
            sql.append(" and creation_time <= '" + params.get("endTime") + "'");
        }
        List<Map> rs = sqlManager.execute(new SQLReady(sql.toString()), Map.class);
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal bank = new BigDecimal(rs.get(0).get("bank").toString());
        BigDecimal alipay = new BigDecimal(rs.get(0).get("alipay").toString());
        BigDecimal wechat = new BigDecimal(rs.get(0).get("wechat").toString());
        BigDecimal cash = new BigDecimal(rs.get(0).get("cash").toString());
        total = total.add(bank).add(alipay).add(wechat).add(cash);
        rs.get(0).put("total", total);
        return ResultUtil.success(rs.get(0));
    }
}
